package com.shengzai.rdd

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo20Student {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf()
    conf.setMaster("local[4]")
    conf.setAppName("join")

    val sc = new SparkContext(conf)

    /**
     * 1、统计总分排名前十学生各科的分数
     *
     */

    val scoreRDD: RDD[String] = sc.textFile("data/score.txt")

    /**
     * 1、取出总分前十的学生
     */
    val sumScoreRDD: RDD[(String, Int)] = scoreRDD
      .map(line => {
        val split: Array[String] = line.split(",")
        (split(0), split(2).toInt)
      })
      .reduceByKey((x, y) => x + y)


    /**
     * 2、按照总分排名取前十
     */
    val top10: Array[String] = sumScoreRDD
      .sortBy(kv => kv._2, ascending = false) // 总分降序排序
      .take(10) //取前十
      .map(kv => kv._1) //取出学号

    /**
     * 3、取出前十前十各科的分数
     *
     */

    val resultRDD: RDD[String] = scoreRDD.filter(line => {
      val id: String = line.split(",")(0)
      //判断学号是否在数组中存在
      top10.contains(id)
    })


    resultRDD.foreach(println)

  }

}
